package com.hsg.common.thirdloginutil.login.fb

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import com.facebook.*
import com.facebook.login.DefaultAudience
import com.facebook.login.LoginBehavior
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.hsg.common.thirdloginutil.bean.ThirdLoginRespond
import com.hsg.common.thirdloginutil.login.LoginInterface
import org.json.JSONObject
import java.util.*

class FacebookLogin(
//    private val activity: Activity,
    private val fragment: Fragment,
    private val loginCallback: (respond: ThirdLoginRespond?) -> Unit
) : LoginInterface {

    private val TAG = "FacebookLogin"
    private val defaultAudience = DefaultAudience.FRIENDS
    private val loginBehavior = LoginBehavior.NATIVE_WITH_FALLBACK
    private val permissions = Arrays.asList("public_profile")
    var loginManager: LoginManager? = null
    var callbackManager: CallbackManager? = null;

    override fun startLogin() {
        loginManager = LoginManager.getInstance()
        callbackManager = CallbackManager.Factory.create()
        LoginManager.getInstance().registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
            override fun onCancel() {
                loginCallback(null)
            }

            override fun onError(error: FacebookException) {
                Log.i(TAG, "login error ${error.message}")
                loginCallback(null)
            }

            override fun onSuccess(result: LoginResult) {
                val respond = ThirdLoginRespond(
                    result.accessToken.userId,
                    result.accessToken.token,
                )
//                loginCallback(respond)
                getProfile(result.accessToken, "name", respond)
            }

        })

        val accessToken = AccessToken.getCurrentAccessToken()
        if (accessToken != null && !accessToken.isExpired) {
            Log.d(TAG, "login result: onSuccess: accessToken != null")
            val fbThirdId = accessToken.userId
            val token = accessToken.token
            Log.d(TAG, "fbThirdId: $fbThirdId")
            val respond = ThirdLoginRespond(
                fbThirdId,
                token,
            )
            getProfile(accessToken, "name", respond)
//            val respond = ThirdLoginRespond(
//                fbThirdId,
//                token,
//            )
//            loginCallback(respond)
        } else {
            Log.d(TAG, "accessToken == null")
            loginManager?.setDefaultAudience(defaultAudience)
            loginManager?.setLoginBehavior(loginBehavior)
//            loginManager?.logInWithReadPermissions(
//                activity,
//                permissions
//            )
            loginManager?.logInWithReadPermissions(
                fragment,
                callbackManager!!,
                permissions
            )
        }
    }

    override fun handleLoginResult(requestCode: Int, resultCode: Int, data: Intent?) {
        callbackManager?.onActivityResult(requestCode, resultCode, data)
    }

    override fun signOut() {
        if (loginManager != null) {
            loginManager?.logOut()
        } else {
            LoginManager.getInstance().logOut()
        }
    }

    /**
     * 获取用户信息
     */
    fun getProfile(accessToken: AccessToken?, requestField: String, respond: ThirdLoginRespond) {
//        println("requestField = $requestField")
        val request = GraphRequest.newMeRequest(
            accessToken
        ) { obj, res ->
            //println(jsonObject)
            val name = obj?.optString("name") ?: ""
            respond.userName = name
            loginCallback(respond)
        }

        val parameters = Bundle()
        parameters.putString("fields", requestField)
        request.parameters = parameters
        request.executeAsync()
    }
}